package cn.mall.framework.wxsdk.core.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import cn.mall.framework.wxsdk.aes.AesException;
import cn.mall.framework.wxsdk.core.api.WxCore;
import cn.mall.framework.wxsdk.core.msg.WeixinAccount;

@Slf4j
public abstract class WxWebEntry {
	
	abstract WeixinAccount init();
	
    public String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	WxCore wxCore = new WxCore(init());
        wxCore.init(request);
        try {
        	log.info("调用微信配置实体:%s", wxCore.getMpAct());
            String echo = wxCore.check();
            if (!echo.isEmpty()) {
                return echo;
            } else {
            	log.error("微信接入验证URL时失败!!!");
                log.error("微信服务器echoStr值: %s", wxCore.getEchostr());
                log.error("SHA1签名echoStr值: %s", echo);
            	return "error";
            }
        } catch (AesException e) {
            log.error("微信接入验证URL时出现异常!!!");
            log.error(e.getLocalizedMessage(), e);
        }
		return null;
    }

    public String doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
    	WxCore wxCore = new WxCore(init());
        wxCore.init(request);
        String result = "error";
        try {
        	log.info("调用微信配置实体:%s", wxCore.getMpAct());
            result = wxCore.handler();
        } catch (Exception e) {
            log.error("解析微信消息时出现异常!!!");
            log.error(e.getLocalizedMessage(), e);
        }
        return result;
    }

}
